<template>
  <div class="app-container">
    <div class="contentBox" ref="contentBox">   
      <el-row>
        <el-text class="title">货位卡</el-text>
      </el-row>
      <div class="tableTitle">
        <el-form ref="queryRef" :model="queryParams" :inline="true" @submit.prevent>
          <el-row>
            <el-col :span="24">
              <div class="pageFlex">
                <div class="partName">货位ID查询</div>
                <el-form-item prop="locationId" style="margin: 0px;flex: 1;border-bottom: 1px solid #ebeef5;">
                  <el-input
                      class="inputBox"
                      v-model="queryParams.locationId"
                      placeholder="请输入货位号查询"
                      @keyup.enter="initData()"
                  />
                </el-form-item>
              </div>
            </el-col>
          </el-row>
        </el-form>
        <el-row>
          <el-col :span="12">
            <div class="pageFlex">
              <div class="partName">货位名称</div>
              <div class="value">{{ form.name }}</div>
            </div>
          </el-col>
          <el-col :span="12">
            <div class="pageFlex">
              <div class="partName">货位编码</div>
              <div class="value">{{ form.locationNo }}</div>
            </div>
          </el-col>
          <el-col :span="12">
            <div class="pageFlex">
              <div class="partName">所属仓库ID</div>
              <div class="value">{{ form.warehouseId }}</div>
            </div>
          </el-col>
          <el-col :span="12">
            <div class="pageFlex">
              <div class="partName">所属货架ID</div>
              <div class="value">{{ form.shelfId }}</div>
            </div>
          </el-col>
          <el-col :span="12">
            <div class="pageFlex">
              <div class="partName">存储数量</div>
              <div class="value">{{ form.quantity }}</div>
            </div>
          </el-col>
          <el-col :span="12">
            <div class="pageFlex">
              <div class="partName">类别</div>
              <div class="value">
                <div v-for="(item, index) in gas_stock_warehouse_type" :key="index" v-show="item.value == form.type">
                  <el-tag :type="item.elTagType" v-if="item.elTagType">{{ item.label }}</el-tag>
                  <div v-else>{{ item.label }}</div>
                </div>
              </div>
            </div>
          </el-col>
        </el-row>
      </div>
      <el-table
        v-loading="loading"
        :data="dataList"
        border
        style="margin-top: 1px;">
        <el-table-column prop="goodsNo" label="商品编码" width="150" :show-overflow-tooltip="true" fixed="left"></el-table-column>
        <el-table-column prop="name" label="商品名称" width="150" :show-overflow-tooltip="true">
          <template #default="scope">
            <div style="max-width: 120px;color: var(--el-color-primary);cursor: pointer;" class="textOverflow1" @click="toPage('/gasManage/stockManage/good-info/printInOutHistory/'+scope.row.id)">{{ scope.row.name }}</div>
          </template>
        </el-table-column>
        <el-table-column prop="cover" label="商品图片" width="80" align="center">
          <template #default="scope">
            <div class="tableImgBox1">
              <el-image class="img" fit="contain" lazy :src="setCoverUrl(scope.row.cover)"
                        @click="handlePreviewShow(setCoverUrl(scope.row.cover))" v-if="scope.row.cover" />
              <div class="emptyBox" v-else>暂无图标</div>
            </div>
          </template>
        </el-table-column>
        <el-table-column prop="barCode" label="商品条码" width="150" :show-overflow-tooltip="true"></el-table-column>
        <el-table-column width="200" :show-overflow-tooltip="true">
          <template #header="scope">
              <div class="pageFlex pageAlignCenter">
                <el-text>市场参考价(本年)</el-text>
                <el-tooltip
                  class="box-item"
                  effect="dark"
                  content="历史最高、历史最低将在您入库之后生成"
                  placement="bottom"
                >
                  <el-icon style="cursor: pointer;"><QuestionFilled /></el-icon>
                </el-tooltip>
              </div>
            </template>
          <template #default="scope">
            <div style="max-width: 180px;font-weight: 500;" class="textOverflow1">当前价格：￥{{scope.row.price}}</div>
            <div style="color: var(--el-color-danger);max-width: 180px;font-weight: 500;" class="textOverflow1">历史最高：￥{{scope.row.maxPrice}}</div>
            <div style="color: var(--el-color-success);max-width: 180px;font-weight: 500;" class="textOverflow1">历史最低：￥{{scope.row.minPrice}}</div>
          </template>
        </el-table-column>
        <el-table-column width="200" :show-overflow-tooltip="true">
          <template #header="scope">
              <div class="pageFlex pageAlignCenter">
                <el-text>采购成本价(本年)</el-text>
                <el-tooltip
                  class="box-item"
                  effect="dark"
                  content="平均成本价、历史最高、历史最低将在您入库之后生成"
                  placement="bottom"
                >
                  <el-icon style="cursor: pointer;"><QuestionFilled /></el-icon>
                </el-tooltip>
              </div>
            </template>
          <template #default="scope">
            <div style="max-width: 180px;font-weight: 500;" class="textOverflow1">当前成本价：￥{{scope.row.costPrice}}</div>
            <div style="color: var(--el-color-info);max-width: 180px;font-weight: 500;" class="textOverflow1">平均成本价：￥{{scope.row.averageCostPrice || 0}}</div>
            <div style="color: var(--el-color-danger);max-width: 180px;font-weight: 500;" class="textOverflow1">历史最高：￥{{scope.row.maxCostPrice}}</div>
            <div style="color: var(--el-color-success);max-width: 180px;font-weight: 500;" class="textOverflow1">历史最低：￥{{scope.row.minCostPrice}}</div>
          </template>
        </el-table-column>
        <el-table-column prop="stock" label="库存" :show-overflow-tooltip="true"></el-table-column>
        <el-table-column prop="spec" label="规格" :show-overflow-tooltip="true"></el-table-column>
        <el-table-column prop="unit" label="单位" :show-overflow-tooltip="true"></el-table-column>
        <template #empty>
          <el-empty description="暂无数据"/>
        </template>
      </el-table>
      <div class="pageFlex pageAlignCenter pageSpaceBetween" style="margin-top: 20px;">
        <div class="totalText">共计 {{total}} 条</div>
        <el-pagination background layout="sizes, prev, pager, next" :total="total" :current-page="queryParams.pageNum" :page-size="queryParams.pageSize" 
          @size-change="handleSizeChange" @current-change="handleCurrentChange"/>
      </div>
      <div class="pageFlex" style="margin-top: 20px;">
        <div class="normalBtn pageFlex pageFlexCenter" @click="handleExport" v-hasPermi="['gasManage:stockManage:locationManage:exportGoods']">
          <el-icon class="normalBtn_icon2"><Download /></el-icon>
          <div class="normalBtn_text">导出</div>
        </div>
        <!-- <div class="normalBtn pageFlex pageFlexCenter" style="margin-left: 10px;" @click="handlePrint">
          <el-icon class="normalBtn_icon2"><Download /></el-icon>
          <div class="normalBtn_text">打印</div>
        </div> -->
      </div>
    </div>
    <el-dialog v-model="printModalShow" fullscreen>
      <div class="printModal" ref="printBox">
        <div style="width: 100%;">
          <el-row>
            <el-text class="printModalTitle">货位卡</el-text>
          </el-row>
          <el-row class="printModalTitleBox">
            <el-col :span="12">
              <div class="pageFlex">
                <div class="partName">货位名称</div>
                <div class="value">{{ form.name }}</div>
              </div>
            </el-col>
            <el-col :span="12">
              <div class="pageFlex">
                <div class="partName">货位ID</div>
                <div class="value">{{ form.id }}</div>
              </div>
            </el-col>
            <el-col :span="12">
              <div class="pageFlex">
                <div class="partName">货位编码</div>
                <div class="value">{{ form.locationNo }}</div>
              </div>
            </el-col>
            <el-col :span="12">
              <div class="pageFlex">
                <div class="partName">所属仓库ID</div>
                <div class="value">{{ form.warehouseId }}</div>
              </div>
            </el-col>
            <el-col :span="12">
              <div class="pageFlex">
                <div class="partName">所属货架ID</div>
                <div class="value">{{ form.shelfId }}</div>
              </div>
            </el-col>
            <el-col :span="12">
              <div class="pageFlex">
                <div class="partName">存储数量</div>
                <div class="value">{{ form.quantity }}</div>
              </div>
            </el-col>
            <el-col :span="24">
              <div class="pageFlex">
                <div class="partName">类别</div>
                <div class="value">
                  <div v-for="(item, index) in gas_stock_warehouse_type" :key="index" v-show="item.value == form.type">{{ item.label }}</div>
                </div>
              </div>
            </el-col>
          </el-row>
          <el-table :data="dataList" class="printModalTableBox" border>
            <el-table-column prop="goodsNo" label="商品编码"></el-table-column>
            <el-table-column prop="name" label="商品名称"></el-table-column>
            <el-table-column prop="cover" label="商品图片" width="80" align="center">
              <template #default="scope">
                <div class="tableImgBox1">
                  <el-image class="img" fit="contain" lazy :src="setCoverUrl(scope.row.cover)" v-if="scope.row.cover" />
                  <div class="emptyBox" v-else>暂无图标</div>
                </div>
              </template>
            </el-table-column>
            <el-table-column prop="barCode" label="商品条码"></el-table-column>
            <el-table-column label="市场参考价(本年)">
              <template #default="scope">
                <div style="font-weight: 500;">当前价格：￥{{scope.row.price}}</div>
                <div style="color: var(--el-color-danger);font-weight: 500;">历史最高：￥{{scope.row.maxPrice}}</div>
                <div style="color: var(--el-color-success);font-weight: 500;">历史最低：￥{{scope.row.minPrice}}</div>
              </template>
            </el-table-column>
            <el-table-column label="采购成本价(本年)">
              <template #default="scope">
                <div style="font-weight: 500;">当前成本价：￥{{scope.row.costPrice}}</div>
                <div style="color: var(--el-color-info);font-weight: 500;">平均成本价：￥{{scope.row.averageCostPrice || 0}}</div>
                <div style="color: var(--el-color-danger);font-weight: 500;">历史最高：￥{{scope.row.maxCostPrice}}</div>
                <div style="color: var(--el-color-success);font-weight: 500;">历史最低：￥{{scope.row.minCostPrice}}</div>
              </template>
            </el-table-column>
            <el-table-column prop="stock" label="库存"></el-table-column>
            <el-table-column prop="spec" label="规格"></el-table-column>
            <el-table-column prop="unit" label="单位"></el-table-column>
          </el-table>
        </div>
      </div>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="handlePrintModalHide">取消</el-button>
          <el-button type="primary" :loading="printDisabled" @click="handlePrintNow">确认打印效果并打印</el-button>
        </div>
      </template>
    </el-dialog>
    <el-image-viewer :url-list="srcList" @close="handlePreviewClose" v-if="showPreview"/>
  </div>
</template>
<script setup>
import {computed, onMounted} from 'vue';
import {useRoute, useRouter} from 'vue-router';
import printJS from 'print-js';
import html2canvas from 'html2canvas';
import { getLocationById, getLocationGoods } from '@/api/gasManage/stockManage/locationManage';
import { ElLoading } from "element-plus";
const { proxy } = getCurrentInstance();
const { gas_stock_warehouse_type } = proxy.useDict("gas_stock_warehouse_type");
const queryParams = ref({
  pageNum: 1,
  pageSize: 10,
  locationId: ''
})
const loading = ref(false);
const total = ref(0);
const dataList = ref([]);
const form = ref({});
function handleQuery(){
  queryParams.value.pageNum = 1;
  getList();
}
async function getList(){
  loading.value = true;
  let data = await getLocationGoodsApi(queryParams.value);
  if(data.length > 0){
    dataList.value = data;
  }else{
    dataList.value = [];
    total.value = 0;
  }
  loading.value = false;
}
function getLocationGoodsApi(params){
  return new Promise((resolve, reject) => {
    getLocationGoods(params).then(res => {
      total.value = Number(res.total);
      resolve(Array.isArray(res.rows) ? res.rows : []);
    }).catch(()=>{
      resolve([]);
    })
  })
}
function handleCurrentChange(e){
  queryParams.value.pageNum = e;
  getList();
}
function handleSizeChange(e){
  if(queryParams.value.pageNum !== 1){
    queryParams.value.pageNum = 1;
  }
  queryParams.value.pageSize = e;
  getList();
}
// ----------------------------------查看图片-------------------------------------
const baseUrl = import.meta.env.VITE_APP_BASE_API;
const showPreview = ref(false);
const srcList = ref([])
const setCoverUrl = computed(()=>{
  return url => {
    if(url){
      return baseUrl+url
    }
    return  ''
  }
})
function handlePreviewShow(link){
  srcList.value = [link];
  showPreview.value = true;
}
function handlePreviewClose(){
  showPreview.value = false;
  srcList.value = [];
}
// ----------------------------页面跳转---------------------
const router = useRouter();
function toPage(link, row){
  let url = link;
  if(row){
    url += row.id
  }
  router.push(url);
}
// ----------------------------导出--------------------------------
function handleExport(){
  proxy.download("/stock/goods/export", {
    ...queryParams.value
  }, `货位卡_${new Date().toLocaleDateString()}.xlsx`);
}
// ---------------------------打印---------------------------------
const printDisabled = ref(false);
const printModalShow = ref(false);
function handlePrint(){
  printModalShow.value = true;
  // var printWindow = window.open('', 'PrintWindow', 'height=600,width=800');
  // var content = document.getElementById('contentBox').cloneNode(true);
  // var html = '<html><head><title>打印页面</title>' +
  //   '<style> @media print { /* 此处与上述样式表一样，可以复用 */ } </style></head><body>' +
  //   content.innerHTML + '</body></html>';
 
  // // 在新窗口中输出打印内容。
  // printWindow.document.write(html);
  // printWindow.document.addEventListener('DOMContentLoaded', function() {
  //   setTimeout(function() {
  //     console.log(2)
  //   }, 500);
  // })
  // 法二
  // proxy.$refs.iframe.contentWindow.document.body.innerHTML = ''  // 清空上一次打印的内容
  // proxy.$refs.iframe.contentWindow.document.write('<html><head><style media="print">@page { margin: 0mm 10mm; }body{margin-top: 50px; text-align: center;}</style></head><body><img src=' + dataURL + '></body></html>')
  // setTimeout(_ => {

  //   // proxy.$refs.iframe.contentWindow.print()
  // }, 0)
}
function handlePrintNow(){
  printDisabled.value = true;
  html2canvas(proxy.$refs.printBox, {
    backgroundColor: null,
    scale: 3
  }).then((canvas) => {
    let dataURL = canvas.toDataURL('image/png')
    printJS({
      printable: dataURL, 
      type: 'image',
      onError: function(error) {
        console.error('打印失败:', error);
        printDisabled.value = false;
      }
    })
    printDisabled.value = false;
  })
}
function handlePrintModalHide(){
  printModalShow.value = false;
  printDisabled.value = false
}
// ----------------------------初始化-----------------------
const route = useRoute();
onMounted(()=>{
  queryParams.value.locationId = route.params.id;
  initData();
})
async function initData(){
  if(queryParams.value.locationId){
    const loading = ElLoading.service({
      lock: true,
      text: '加载中~',
      background: 'rgba(0, 0, 0, 0.7)',
    })
    let result = await getWarehouseDataApi(queryParams.value.locationId);
    form.value = result;
    handleQuery();
    loading.close();
  }else{
    proxy.$modal.msgError('请先输入货位ID!');
  }
}
function getWarehouseDataApi(id){
  return new Promise((resolve, reject) => {
    getLocationById(id).then(res => {
      resolve(res.data);
    }).catch(() => {
      resolve(false)
    })
  })
}
</script>
<style scoped>
.printModal{
  width: 100%;
}
.printModalTitle{
  width: 100%;
  height: 60px;
  line-height: 60px;
  font-size: 18px;
  text-indent: 1em;
  font-weight: bold;
  border-top: 1px solid #EBEEF5;
  border-left: 1px solid #EBEEF5;
  border-right: 1px solid #EBEEF5;
  background-color: #F2F3F5;
}
.pageFlex{
  display: flex;
}
.printModalTitleBox{
  width: 100%;
  border-top: 1px solid #EBEEF5;
  border-right: 1px solid #EBEEF5;
}
.partName{
  width: 120px;
  height: 40px;
  line-height: 40px;
  font-size: 15px;
  text-indent: 1em;
  border-left: 1px solid #EBEEF5;
  border-right: 1px solid #EBEEF5;
  border-bottom: 1px solid #EBEEF5;
}
.value{
  flex: 1;
  height: 40px;
  line-height: 40px;
  padding: 0 20px;
  color: #4E5969;
  border-bottom: 1px solid #EBEEF5;
}
.printModalTableBox{
  margin-top: 1px;
}
</style>
<style lang='scss' scoped>
@import "@/assets/styles/public.scss";
.normalBtn{
  &_icon2{
    margin-right: 10px;
    color: $normalBtnColor;
  }
  &_text{
    color: $normalBtnColor;
  }
  &:hover{
    outline: 1px solid $normalBtnColor;
  }
}
.app-container{
  width: 100%;
  min-height: calc(100vh - 66px);
  background: #F8F8F9;
}
.contentBox{
  width: 100%;
  background-color: #FFFFFF;
  border-radius: 5px;
  box-sizing: border-box;
  padding: 12px;
  .selectBox{
    width: 100%;
    background-color: $formBgSet;
    .title{
      font-size: 20px;
      width: 120px;
      height: 40px;
      line-height: 40px;
      text-align: center;
      color: white;
      font-size: 16px;
      background: var(--el-color-primary);
    }
    .dateLabel{
      color: $colorText1;
      line-height: 40px;
    }
  }
  .title{
    width: 100%;
    height: 60px;
    line-height: 60px;
    font-size: 18px;
    text-indent: 1em;
    font-weight: bold;
    border-top: 1px solid $borderColor;
    border-left: 1px solid $borderColor;
    border-right: 1px solid $borderColor;
    background-color: $formBgSet;
  }
  .tableTitle{
    width: 100%;
    border-top: 1px solid $borderColor;
    border-right: 1px solid $borderColor;
    .partName{
      width: 120px;
      height: 40px;
      line-height: 40px;
      font-size: 15px;
      text-indent: 1em;
      border-left: 1px solid $borderColor;
      border-right: 1px solid $borderColor;
      border-bottom: 1px solid $borderColor;
    }
    .value{
      flex: 1;
      height: 40px;
      line-height: 40px;
      padding: 0 20px;
      color: $colorText1;
      border-bottom: 1px solid $borderColor;
    }
    &:deep(.el-form-item){
      margin: 0;
      flex: 1;
      border-bottom: 1px solid $borderColor;
    }
  }
  .inputBox{
    width: 300px;
    padding: 0 9px;
    &:deep(.el-input__wrapper){
      box-shadow: none;
    }
  }
}
</style>